package com.adgox.tiantianbiting.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.TtbtApplication;
import com.adgox.tiantianbiting.bean.BaseResponseBean;
import com.adgox.tiantianbiting.bean.ProgramDetailBean;
import com.adgox.tiantianbiting.bean.RandomRedPacketBean;
import com.adgox.tiantianbiting.bean.ShareUrlBean;
import com.adgox.tiantianbiting.bean.SignDayBean;
import com.adgox.tiantianbiting.bean.SignWeekBean;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.main.MainActivity;
import com.adgox.tiantianbiting.main.StartActivity;
import com.adgox.tiantianbiting.mine.login.LoginActivity;
import com.adgox.tiantianbiting.mine.tingCoinRecord.TingCoinRecordActivity;
import com.adgox.tiantianbiting.net.callback.JsonCallback;
import com.adgox.tiantianbiting.redpacket.sign.SignActivity;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rae.swift.session.SessionManager;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import java.util.HashMap;
import java.util.List;

/**
 * Created by tang on 2019/1/14.
 */

public class DialogUtils {

    private static Dialog dialog;
    private static Dialog signDialog;
    private static Dialog redDialog;
    private static Dialog successDialog;
    private static Dialog shareDialog;

    public static void showLoadingDialog(Context context) {
        if (dialog != null) return;
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.dialog_loading, null);

        dialog = new Dialog(context);
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.setDimAmount(0.2f);
        dialog.show();
    }

    public static void dismiss() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    public static void showSignDialog(final Context context, SignWeekBean bean) {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_sign, null);
        signDialog = new Dialog(context, R.style.TransparentDialog);
        signDialog.setContentView(view);

        ImageView ivSign1 = signDialog.findViewById(R.id.iv_sign1);
        ImageView ivSign2 = signDialog.findViewById(R.id.iv_sign2);
        ImageView ivSign3 = signDialog.findViewById(R.id.iv_sign3);
        ImageView ivSign4 = signDialog.findViewById(R.id.iv_sign4);
        ImageView ivSign5 = signDialog.findViewById(R.id.iv_sign5);
        ImageView ivSign6 = signDialog.findViewById(R.id.iv_sign6);
        ImageView ivSign7 = signDialog.findViewById(R.id.iv_sign7);
        ImageView ivButton = signDialog.findViewById(R.id.iv_button);
        TextView tvToSign = signDialog.findViewById(R.id.tv_to_sign);
        ImageView ivClose = signDialog.findViewById(R.id.iv_close);

        if (bean != null) {
            List<SignDayBean> subSignInBo = bean.getSubSignInBo();

            ivSign1.setImageResource(subSignInBo.get(0).getSignStatus() == 1 ? R.drawable.icon_check_1 : R.drawable.icon_uncheck_1);
            ivSign2.setImageResource(subSignInBo.get(1).getSignStatus() == 1 ? R.drawable.icon_check_2 : R.drawable.icon_uncheck_2);
            ivSign3.setImageResource(subSignInBo.get(2).getSignStatus() == 1 ? R.drawable.icon_check_3 : R.drawable.icon_uncheck_3);
            ivSign4.setImageResource(subSignInBo.get(3).getSignStatus() == 1 ? R.drawable.icon_check_4 : R.drawable.icon_uncheck_4);
            ivSign5.setImageResource(subSignInBo.get(4).getSignStatus() == 1 ? R.drawable.icon_check_5 : R.drawable.icon_uncheck_5);
            ivSign6.setImageResource(subSignInBo.get(5).getSignStatus() == 1 ? R.drawable.icon_check_6 : R.drawable.icon_uncheck_6);
            ivSign7.setImageResource(subSignInBo.get(6).getSignStatus() == 1 ? R.drawable.icon_check_7 : R.drawable.icon_uncheck_7);

        }

        tvToSign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signDialog.dismiss();
                if (SessionManager.getDefault().isLogin()) {
                    context.startActivity(new Intent(context, SignActivity.class));
                } else {
                    context.startActivity(new Intent(context, LoginActivity.class));
                }
            }
        });

        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signDialog.dismiss();
            }
        });

        ivButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!SessionManager.getDefault().isLogin()) {
                    signDialog.dismiss();
                    context.startActivity(new Intent(context, LoginActivity.class));
                    return;
                }
                showLoadingDialog(context);
                OkGo.<BaseResponseBean<UserInfo>>get(ApiConstant.BASE_URL + ApiConstant.SIGN)
                        .params("userId", ((UserInfo) SessionManager.getDefault().getUser()).getId())
                        .execute(new JsonCallback<BaseResponseBean<UserInfo>>() {
                            @Override
                            public void onSuccess(Response<BaseResponseBean<UserInfo>> response) {
                                dismiss();
                                if ("0".equals(response.body().getCode())){
                                    Toast.makeText(context, "签到成功", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(context, "签到失败", Toast.LENGTH_SHORT).show();
                                }
                                signDialog.dismiss();
                            }
                        });

            }
        });

        Window window = signDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.setDimAmount(0.8f);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        signDialog.show();
    }

    public static void checkRandomRed(final int userId, final Context context, final String pageConfig) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("pageConfig",pageConfig);
        map.put("userId ",userId);
        Gson gson = new Gson();
        String s = gson.toJson(map);

        OkGo.<BaseResponseBean<RandomRedPacketBean>>post(ApiConstant.BASE_URL+ApiConstant.RANDOM_RED_PACKET)
                .upJson(s)
                .execute(new JsonCallback<BaseResponseBean<RandomRedPacketBean>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<RandomRedPacketBean>> response) {
                        if ("001".equals(response.body().getCode()) && response.body().getData()!=null){

                            if (response.body().getData().getState() == 1){
                                //有红包
                                showRedPacketDialog(userId,context,pageConfig);
                            }
                        }
                    }
                });

    }

    private static void showRedPacketDialog(final int userId, final Context context, final String pageConfig){
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_red_packet, null);
        redDialog = new Dialog(context, R.style.TransparentDialog);
        redDialog.setContentView(view);

        ImageView ivRed1 = redDialog.findViewById(R.id.iv_red_1);
        ImageView ivRed2 = redDialog.findViewById(R.id.iv_red_2);

        AlphaAnimation alphaAni1 = new AlphaAnimation(0f, 1f);
        alphaAni1.setRepeatCount(Animation.INFINITE);
        alphaAni1.setRepeatMode(Animation.REVERSE);
        alphaAni1.setDuration(1000);
        ivRed1.setAnimation(alphaAni1);

        AlphaAnimation alphaAni2 = new AlphaAnimation(1f, 0f);
        alphaAni2.setRepeatCount(Animation.INFINITE);
        alphaAni2.setRepeatMode(Animation.REVERSE);
        alphaAni2.setDuration(1000);
        ivRed2.setAnimation(alphaAni2);

        ivRed1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                redDialog.dismiss();
//                showRedPacketSuccessDialog(context);
                getRandomRedPacket(userId,context,pageConfig);
            }
        });

        ivRed2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                redDialog.dismiss();
//                showRedPacketSuccessDialog(context);
                getRandomRedPacket(userId,context,pageConfig);
            }
        });

        redDialog.setCanceledOnTouchOutside(false);
        Window window = redDialog.getWindow();
        window.setDimAmount(0f);
        window.setGravity(Gravity.RIGHT | Gravity.BOTTOM);
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.y = 500;
        attributes.x = 150;
        redDialog.show();

    }

    private static void getRandomRedPacket(final int userId, final Context context, final String pageConfig) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("pageConfig",pageConfig);
        map.put("userId ",userId);
        Gson gson = new Gson();
        String s = gson.toJson(map);
        OkGo.<BaseResponseBean<RandomRedPacketBean>>post(ApiConstant.BASE_URL+ApiConstant.GET_RANDOM_RED_PACKET)
                .upJson(s)
                .execute(new JsonCallback<BaseResponseBean<RandomRedPacketBean>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<RandomRedPacketBean>> response) {
                        if ("0".equals(response.body().getCode())&&response.body().getData()!=null){
                            redDialog.dismiss();
                            View view = LayoutInflater.from(context).inflate(R.layout.dialog_red_packet_success, null);
                            successDialog = new Dialog(context, R.style.TransparentDialog);
                            successDialog.setContentView(view);
                            TextView tvTips = successDialog.findViewById(R.id.tv_tips);
                            TextView tvAmount = successDialog.findViewById(R.id.tv_amount);
                            TextView tvButton = successDialog.findViewById(R.id.tv_button);
                            ImageView ivCancel = successDialog.findViewById(R.id.iv_cancel);

                            tvTips.setText("送你"+response.body().getData().getTb()+"听币  听越多赚越多!");
                            tvAmount.setText(response.body().getData().getTb()+"");

                            tvButton.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    context.startActivity(new Intent(context, TingCoinRecordActivity.class));
                                }
                            });

                            ivCancel.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    successDialog.dismiss();
                                }
                            });
                            successDialog.setCanceledOnTouchOutside(false);
                            Window window = successDialog.getWindow();
                            window.setGravity(Gravity.CENTER);
                            window.setDimAmount(0.8f);
                            successDialog.show();
                        } else {
                            redDialog.dismiss();
                            Toast.makeText(context, "领取失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

//    public static void showRedPacketSuccessDialog(Context context){
//        View view = LayoutInflater.from(context).inflate(R.layout.dialog_red_packet_success, null);
//        successDialog = new Dialog(context, R.style.TransparentDialog);
//        successDialog.setContentView(view);
//        TextView tvTips = successDialog.findViewById(R.id.tv_tips);
//        TextView tvAmount = successDialog.findViewById(R.id.tv_amount);
//        TextView tvButton = successDialog.findViewById(R.id.tv_button);
//        ImageView ivCancel = successDialog.findViewById(R.id.iv_cancel);
//        ivCancel.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                successDialog.dismiss();
//            }
//        });
//        successDialog.setCanceledOnTouchOutside(false);
//        Window window = successDialog.getWindow();
//        window.setGravity(Gravity.CENTER);
//        window.setDimAmount(0.8f);
//        successDialog.show();
//    }

    public static void showShareDialog(final Context context, final String url){
        if (!SessionManager.getDefault().isLogin()){
            Toast.makeText(context, "请先登录再继续操作", Toast.LENGTH_SHORT).show();
            return;
        }
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_share, null);
        shareDialog = new Dialog(context, R.style.TransparentDialog);
        shareDialog.setContentView(view);
        LinearLayout llWX = shareDialog.findViewById(R.id.ll_wx);
        LinearLayout llWXMoments = shareDialog.findViewById(R.id.ll_wx_moments);
        TextView tvCancel = shareDialog.findViewById(R.id.tv_cancel);

        llWX.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendMessageToWX.Req req = SharePre(context,url);
                req.scene = SendMessageToWX.Req.WXSceneSession;
                TtbtApplication.wxapi.sendReq(req);
                shareDialog.dismiss();
            }
        });
        llWXMoments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendMessageToWX.Req req = SharePre(context,url);
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                TtbtApplication.wxapi.sendReq(req);
                shareDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (shareDialog!=null) shareDialog.dismiss();
            }
        });

        Window window = shareDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);

        shareDialog.setCanceledOnTouchOutside(false);
        shareDialog.show();
    }

    public static SendMessageToWX.Req SharePre(final Context context, String url){
        if (!isWXAppInstall(context)) return null;
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = url+"?srcUserId="+((UserInfo)SessionManager.getDefault().getUser()).getId();
        WXMediaMessage msg = new WXMediaMessage();
        msg.title="天天必听";
        msg.description = "天天必听";
        msg.mediaObject = webPage;
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webPage");
        req.message = msg;
        return req;
    }


    private static String buildTransaction(String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private static boolean isWXAppInstall(Context context) {
        if (TtbtApplication.wxapi.isWXAppInstalled()) {
            return true;
        } else {
            Toast.makeText(context, "请安装微信客户端", Toast.LENGTH_SHORT).show();
            return false;
        }
    }
}
